package com.riku.security.service.impl;

import com.riku.security.common.SeSecurityException;
import com.riku.security.common.SnowFlake;
import com.riku.security.mapper.SeServiceMapper;
import com.riku.security.mapper.SeServiceUserMapper;
import com.riku.security.model.SeService;
import com.riku.security.model.SeServiceUser;
import com.riku.security.service.SeServiceService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;

/**
 * Created by NANC on 2021/5/16.
 */
@Service
public class SeServiceServiceImpl implements SeServiceService {

    @Autowired
    private SeServiceMapper seServiceMapper;

    @Autowired
    private SeServiceUserMapper seServiceUserMapper;

    @Autowired
    private SnowFlake snowFlake;

    @Override
    @Transactional
    public void insertService(String serviceCode,String serviceName,String userId,String userName) {
        int count = seServiceMapper.countByServiceCode(serviceCode);
        if (count > 0) {
            throw new SeSecurityException(SeSecurityException.ERROR_EXSIT);
        }

        SeService seService = new SeService();
        seService.setId(snowFlake.nextId());
        seService.setServiceCode(serviceCode);
        seService.setServiceName(serviceName);
        seServiceMapper.insert(seService);

        SeServiceUser seUser = new SeServiceUser();
        seUser.setId(snowFlake.nextId());
        seUser.setServiceCode(serviceCode);
        seUser.setUserId(userId);
        seUser.setUserName(userName);
        int userCount = seServiceUserMapper.countByServiceCodeUser(seUser);

        if (userCount == 0) {
            seServiceUserMapper.insert(seUser);
        }
    }

    @Override
    public void deleteService(Long id) {
        seServiceMapper.deleteByPrimaryKey(id);
    }

    @Override
    public List<SeServiceUser> selectServiceUser(String serviceCode,String userName) {
        SeServiceUser query = new SeServiceUser();
        query.setServiceCode(serviceCode);
        query.setUserName(userName);
        return seServiceUserMapper.selectByParam(query);
    }

    @Override
    public void insertServiceUser(String serviceCode, String userId, String userName) {
        SeServiceUser seUser = new SeServiceUser();
        seUser.setId(snowFlake.nextId());
        seUser.setServiceCode(serviceCode);
        seUser.setUserId(userId);
        seUser.setUserName(userName);

        int count = seServiceUserMapper.countByServiceCodeUser(seUser);
        if (count > 0) {
            throw new SeSecurityException(SeSecurityException.ERROR_EXSIT);
        }

        seServiceUserMapper.insert(seUser);
    }


    @Override
    public void deleteServiceUser(Long id) {
        seServiceUserMapper.deleteByPrimaryKey(id);
    }
}
